//
//  ZQFileManager.m
//  BuDeJie
//
//  Created by 仲琦 on 16/4/8.
//  Copyright © 2016年 仲琦. All rights reserved.
//

#import "ZQFileManager.h"

@implementation ZQFileManager

+ (void)removeDirectoryPath:(NSString *)cachePath
{
    
    
    NSFileManager *manager = [NSFileManager defaultManager];
    
    BOOL isDirectory;
    BOOL isExist = [manager fileExistsAtPath:cachePath isDirectory:&isDirectory];
    
    if (!isExist || !isDirectory) {
        // 报错:抛异常
        NSException *excp = [NSException exceptionWithName:@"filePathError" reason:@"传错,必须传文件夹路径" userInfo:nil];
        
        [excp raise];
        
    }

    
    
    //获取cache文件目录下所有的文件
    NSArray *path = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:cachePath error:nil];
    
    //遍历文件
    for (NSString *sub in path) {
        
        //拼接路径
        NSString *filepath = [cachePath stringByAppendingPathComponent:sub];
        
        //删除文件
        [[NSFileManager defaultManager] removeItemAtPath:filepath error:nil];
        
    }
}

+ (NSInteger)getDictionarySize:(NSString *)path
{
    
        //获取文件管理者
    NSFileManager *manager = [NSFileManager defaultManager];
    
    BOOL isDirectory;
    BOOL isExist = [manager fileExistsAtPath:path isDirectory:&isDirectory];
    
    if (!isExist || !isDirectory) {
        // 报错:抛异常
        NSException *excp = [NSException exceptionWithName:@"filePathError" reason:@"传错,必须传文件夹路径" userInfo:nil];
        
        [excp raise];
        
    }

    /*
     获取这个文件夹中所有文件路径,然后累加 = 文件夹的尺寸
     */
    
//    获取 cache文件下的 default 文件 路径
//    NSString *defaultPath = [path stringByAppendingPathComponent:@"default"];

    
    //获取文件夹下所有的文件
    NSArray *subs = [manager subpathsAtPath:path];
    NSInteger totalSize = 0 ;
    
    //遍历文件夹下的所有文件
    for (NSString *sub in subs) {
        
        //拼接路径
        NSString *filePaht = [path stringByAppendingPathComponent:sub];
        
        //排除文件夹
        BOOL isDirectory;
        //判断文件是否存在 是否是文件夹
        BOOL isExist = [manager fileExistsAtPath:filePaht isDirectory:&isDirectory];
        if (!isExist || isDirectory) continue;
        
        //隐藏文件
        if ([filePaht containsString:@".DS"]) continue;
        
        // attributesOfItemAtPath:获取文件属性
        NSDictionary *attr = [manager attributesOfItemAtPath:filePaht error:nil];
        
        //获取文件大小
        NSInteger size = [attr fileSize];
        
        //计算总大小
        totalSize += size;
        
        
    }
    
    return totalSize;
}
@end
